﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using System.IO;
using System.Threading;
using System.Web.UI;
using UpdateAuto;

namespace HRM
{
    public partial class frmAutoUpdateTemplate : Form
    {
        public string TemFolder = "";
        public string FileList = "";
        public bool FinishUpdate = false;
        //
        public frmAutoUpdateTemplate()
        {
            InitializeComponent();
        }
        
        private void frmAutoUpdate_Load(object sender, EventArgs e)
        {
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            StartUpdate();
        }

        private void workerGetFileList_DoWork(object sender, DoWorkEventArgs e)
        {
            // fetch the list of filenames from the web service
            MtomClient wcfMtom = Service.Mtom();
            string[] files = wcfMtom.GetFilesTemplateList();
            // set the result with the return value (available to workerGetFileList_RunWorkerCompleted method as e.Result)
            e.Result = files;
        }

        //Bắt đầu Update
        private void StartUpdate()
        {
            workerGetFileList.RunWorkerAsync();
            
            // set the default save folder
            TemFolder = Path.GetTempPath() + "HRMUpdate\\ExportTemplate";
            if (!Directory.Exists(TemFolder))
                Directory.CreateDirectory(TemFolder);

            // configure the 'TaskPanel' which is used to dynamically show a progress bar + status message for each file transfer operation
            this.tpnCapNhat.RemoveItemsWhenFinished = true;
            this.tpnCapNhat.RemoveItemsOnError = false;
            this.tpnCapNhat.AutoSizeForm = false;

            // init the ThreadPool MaxThread size to the value in the control
            ThreadPool.SetMaxThreads(5, 5);
        }

        #region download code

        /// <summary>
        /// This method is used as a thread start function.
        /// The parameter is a Triplet because the ThreadStart can only take one object parameter
        /// </summary>
        /// <param name="triplet">First=guid; Second=path; Third=offset</param>
        private void DownloadFile(object triplet)
        {
            string guid = (triplet as Triplet).First.ToString();
            string path = (triplet as Triplet).Second.ToString();
            long offset = Int64.Parse((triplet as Triplet).Third.ToString());

            FileTransferDownload ftd = new FileTransferDownload();
            ftd.Guid = guid;
            // set up the chunking options
            ftd.AutoSetChunkSize = true;

            // set the remote file name and start the background worker
            ftd.RemoteFileName = Path.GetFileName(path);
            if (ftd.RemoteFileName.ToLower().Contains("autoupdate.exe"))
                ftd.LocalSaveFolder = Application.StartupPath.ToLower() + "\\AutoUpdate";
            else
                ftd.LocalSaveFolder = TemFolder;

            ftd.IncludeHashVerification = true;
            ftd.ProgressChanged += new ProgressChangedEventHandler(ft_ProgressChanged);
            ftd.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ft_RunWorkerCompleted);
            ftd.RunWorkerSync(new DoWorkEventArgs(0));
        }

        void ft_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string guid = (sender as FileTransferBase).Guid;
            if (e.Error != null)
            {
                this.tpnCapNhat.EndOperation(guid, e.Error);
            }
            else if (e.Cancelled)
            {
                this.tpnCapNhat.EndOperation(guid, new Exception("Cancelled"));
            }
            else
            {
                this.tpnCapNhat.EndOperation(guid, null);
                if (this.tpnCapNhat.List.Count == 0)
                {
                    //if (MessageBox.Show("Phần mềm đã cập nhật bản mới!\nHãy nhấn nút OK để bắt đầu cập nhật hoặc Cancel để cập nhật sau", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    //{
                    //    System.Diagnostics.Process.Start(Application.StartupPath + "\\AutoUpdate\\AutoUpdate.exe", "1 " + TemFolder.Trim().Replace(" ", "$$") + " " + FileList);
                    //    //isFirstLoad = true;
                    //    Application.Exit();
                    //}
                    //else
                    //{
                    //    FinishUpdate = true;
                    //}

                    if (!Directory.Exists(Path.Combine(Application.StartupPath.ToLower(), "ExportTemplate")))
                        Directory.CreateDirectory(Path.Combine(Application.StartupPath.ToLower(), "ExportTemplate"));
                    //

                    string []sArrFile = FileList.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string sFile in sArrFile)
                    {
                        //Copy file từ thư mục temp vào thư mục cài đặt
                        if (sFile.ToLower().Contains("hrm.resources.dll"))
                            File.Copy(TemFolder + "\\" + Path.GetFileName(sFile.Replace("$$", " ")),
                                Application.StartupPath.ToLower().Replace("\\autoupdate", "\\vi-VN") + "\\" + "" + "ExportTemplate\\" + Path.GetFileName(sFile.Replace("$$", " ")), true);
                        else
                            File.Copy(TemFolder + "\\" + Path.GetFileName(sFile.Replace("$$", " ")),
                                Application.StartupPath.ToLower().Replace("\\autoupdate", "") + "\\" + "ExportTemplate\\" + Path.GetFileName(sFile.Replace("$$", " ")), true);
                    }

                    //Copy xong thì xóa
                    foreach (string sFile in sArrFile)
                    {
                        File.Delete(TemFolder + "\\" + Path.GetFileName(sFile.Replace("$$", " ")));
                    }

                    //
                    MessageBox.Show("Hoàn thành cập nhật mẫu biểu, tiếp tục sử dụng chương trình");
                    this.DialogResult = DialogResult.OK;
                }
            }
        }

        void ft_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tpnCapNhat.ProgressChanged((sender as FileTransferBase).Guid, e.ProgressPercentage, e.UserState.ToString());
        }

        #endregion

        #region Get Server File List code
        /// <summary>
        /// This method fetches a string[] of filenames from the Upload folder on the server.
        /// </summary>
        /// 

        private void workerGetFileList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Không thấy file trên server\n" + e.Error.Message, "Thông báo");
            }
            else
            {
                this.lstDownloadFiles.Items.Clear();

                // copy the list of filenames into the listbox
                foreach (string s in e.Result as string[])
                    this.lstDownloadFiles.Items.Add(s);
                if (this.lstDownloadFiles.Items.Count > 0)
                {
                    foreach (ListViewItem item in this.lstDownloadFiles.Items)
                    {
                        if (!item.Text.ToLower().Contains("autoupdate.exe"))
                            FileList = FileList + " " + item.Text.Replace(" ", "$$");
                        string guid = Guid.NewGuid().ToString();
                        this.tpnCapNhat.AddOperation(new TaskPanelOperation(guid, String.Format("Cập nhật file {0}", Path.GetFileName(item.Text)), ProgressBarStyle.Blocks));
                        ThreadPool.QueueUserWorkItem(new WaitCallback(this.DownloadFile), new Triplet(guid, item.Text, 0));
                    }


                    
                }
            }

            
        }

        #endregion

        private void cmdExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
